#!/bin/bash

# 设置数据库和系统变量
DB_NAME="authCode"
DB_USER="root"
DB_PASSWORD="password"
PROJECT_DIR="/var/flask_app"
GIT_REPO="https://gitee.com/kiko9527/auth-info.git"
SCRIPT_FILE="/path/to/your_script.sql"
FLASK_APP="AuthInfo.py"
DOMAIN="inpost2.xyz"

# 更新系统并安装必要的软件包
echo ">>> 更新系统包并安装依赖..."
sudo apt-get update

sudo apt-get install -y python3.9 python3.9-venv python3.9-distutils python3.9-dev git mysql-server-5.7 nginx

# 启动并配置 MySQL
echo ">>> 启动 MySQL 服务..."
sudo systemctl start mysql
sudo systemctl enable mysql

echo ">>> 配置 MySQL root 用户密码并创建数据库..."
sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${DB_PASSWORD}';"
sudo mysql -e "CREATE DATABASE ${DB_NAME};"

echo ">>> 执行数据库脚本..."
mysql -u ${DB_USER} -p${DB_PASSWORD} ${DB_NAME} < ${SCRIPT_FILE}

# 克隆 Flask 项目代码
echo ">>> 克隆 Flask 项目代码到 ${PROJECT_DIR}..."
git clone ${GIT_REPO} ${PROJECT_DIR}

# 进入项目目录并创建虚拟环境
cd ${PROJECT_DIR}
echo ">>> 创建虚拟环境并安装依赖..."
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# 配置 Flask 环境变量
echo ">>> 设置 Flask 环境变量..."
export FLASK_APP=${FLASK_APP}
export FLASK_ENV=production
export DATABASE_URL="mysql+pymysql://${DB_USER}:${DB_PASSWORD}@localhost/${DB_NAME}"

# 配置 Nginx
echo ">>> 配置 Nginx 反向代理..."
sudo tee /etc/nginx/sites-available/flask_app <<EOF
server {
    listen 80;
    server_name ${DOMAIN};

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
EOF

sudo ln -s /etc/nginx/sites-available/flask_app /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx

# 配置 Systemd 服务
echo ">>> 配置 Systemd 服务..."
sudo tee /etc/systemd/system/flask_app.service <<EOF
[Unit]
Description=Gunicorn instance to serve Flask application
After=network.target

[Service]
User=$(whoami)
Group=www-data
WorkingDirectory=${PROJECT_DIR}
Environment="PATH=${PROJECT_DIR}/venv/bin"
ExecStart=${PROJECT_DIR}/venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 ${FLASK_APP}:app

[Install]
WantedBy=multi-user.target
EOF

# 启动并启用服务
echo ">>> 启动并启用 Flask 服务..."
sudo systemctl daemon-reload
sudo systemctl start flask_app
sudo systemctl enable flask_app

echo ">>> 部署完成！Flask 应用已经在后台运行。"
